package com.example.doer.reading.AppActivities;

import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.ab.image.AbImageLoader;
import com.example.doer.reading.AppDataModel.CircleImageView;
import com.example.doer.reading.AppDataModel.ReplyAnswer;
import com.example.doer.reading.AppDataModel.TopicReply;
import com.example.doer.reading.R;
import com.example.doer.reading.global.MyApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ab.util.AbToastUtil.showToast;

/**
 * Created by 严旭江 on 2017/7/20.
 */
//回复Reply的界面
public class ReplyAnswerActivity extends AbActivity implements View.OnClickListener {
    Toolbar toolbar;//标题栏
    ListView answerListView;
    AnswerListAdapter answerListAdapter;//适配器
    TopicReply receivedTopicReply;//跳转Activity传递收到的TopicReply
    AbHttpUtil abHttpUtil;
    AbImageLoader abImageLoader;
    List<ReplyAnswer> replyAnswerList = new ArrayList<>();
    //点击回复弹出回复PopWindow
    private LinearLayout myAnswerViewLayout;
    private PopupWindow myPopupWindow;//点击回复弹出回复框
    private int myPopupWindowWidth;
    private int myPopupWindowHeight;
    private int mScreenWidth;//屏幕的宽度 用于放PopWindow
    @Override
    public void onCreate(Bundle savedInstancetype){
        abImageLoader = AbImageLoader.getInstance(ReplyAnswerActivity.this);
        super.onCreate(savedInstancetype);
        setAbContentView(R.layout.activity_reply_answer);
        abHttpUtil = AbHttpUtil.getInstance(ReplyAnswerActivity.this);
        /**
         * 获取传递收到的数据   TopicReply对象
         */
        receivedTopicReply = (TopicReply)getIntent().getSerializableExtra("topicObjWithReply_TO_ReplyAnswer_Activity");
        answerListView = (ListView)findViewById(R.id.ReplyAnswerListView);
        String testUserID = MyApplication.user.getUserID();
        String url = "http://192.168.191.1/Reading/ReplyServlet?Action=down&userID="+testUserID +"&answerID="+receivedTopicReply.getReplyID();
        abHttpUtil.get(url, new AbStringHttpResponseListener() {
            @Override
            public void onSuccess(int i, String s) {
                try {
                    JSONArray jsonArray = new JSONObject(s).getJSONArray("ReplyInit");
                    JSONObject jsonObject;
                    String theFourthID,theFourthUserID,theFourthUserName,theFourthFromReplyID,
                            theFourthContent;
                    String theFourthCreateDate;
                    ReplyAnswer replyAnswer;
                    for(int j =0;j<jsonArray.length();j++){
                        jsonObject = jsonArray.getJSONObject(j);
                        theFourthID = jsonObject.getString("replyID");
                        theFourthUserID = jsonObject.getString("replyFromUserID");
                        theFourthUserName = jsonObject.getString("replyFromUserName");
                        theFourthFromReplyID = jsonObject.getString("replyFromAnswerID");
                        theFourthContent = jsonObject.getString("replyContent");
                        theFourthCreateDate = jsonObject.getString("replyDate");
                        replyAnswer = new ReplyAnswer(theFourthID, theFourthUserID, theFourthUserName, theFourthFromReplyID, theFourthContent, theFourthCreateDate);
                        replyAnswerList.add(replyAnswer);
                    }//end for
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onStart() {
            }
            @Override
            public void onFinish() {

            }
            @Override
            public void onFailure(int i, String s, Throwable throwable) {
                showToast(ReplyAnswerActivity.this,"四级连接失败");
            }
        });
        //返回和回复按钮点击事件
        ((TextView)findViewById(R.id.AnswerReplyActivity_BtnReplyThird)).setOnClickListener(this);
        ((Button)findViewById(R.id.AnswerReplyActivity_BtnReturn)).setOnClickListener(this);

        answerListAdapter = new AnswerListAdapter(replyAnswerList, R.layout.topic_reply_answer_listview);
        answerListView.setAdapter(answerListAdapter);
    }
    class AnswerListAdapter extends BaseAdapter{
        List<ReplyAnswer> answerList;
        int resID;//layout布局
        /**
         *
         * @param theAnswerList  所有的ReplyAnswer对象
         * @param theResID 布局
         */
        public AnswerListAdapter(List<ReplyAnswer> theAnswerList,int theResID){
            answerList = theAnswerList;
            resID = theResID;
        }
        //实现适配器
        @Override
        public int getCount(){
            return answerList.size();
        }
        @Override
        public ReplyAnswer getItem(int position) {
            return answerList.get(position);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(ReplyAnswerActivity.this).inflate(resID,null);
            final ReplyAnswer replyAnswer = answerList.get(position);
            //用户头像
            CircleImageView answerUserImg = (CircleImageView)convertView.findViewById(R.id.answerUserImg);
            //用户名字
            TextView answerUserName = (TextView)convertView.findViewById(R.id.answerUserName);
            //回复内容
            TextView answerContent = (TextView)convertView.findViewById(R.id.answerContent);
            answerContent.setText(replyAnswer.getAnswerContent());
            //回复事件
            TextView answerTime = (TextView)convertView.findViewById(R.id.answerTime);
            answerTime.setText(replyAnswer.getTime());
            //回复按钮  设置点击事件  弹出PopWindow
            TextView answer = (TextView)convertView.findViewById(R.id.answerUser);
            /**
             * 根据用户头像设置头像 replyAnswer.getUserID
             */
            String url = "http://192.168.191.1/Reading/ImageDoServlet?Action=download&Category=UserLogo&ImageName="+MyApplication.user.getUserID();
            abImageLoader.display(answerUserImg,url,300,300);

            answerUserName.setText(replyAnswer.getUserName());
            /**
             * 回复点击事件
             */
            answer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPopWindow(v,replyAnswer);
                }
            });
            return convertView;
        }//end getView
        public void addAnswer(ReplyAnswer replyAnswer){
            answerList.add(replyAnswer);
            notifyDataSetChanged();
        }
    }//end adapter

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.AnswerReplyActivity_BtnReplyThird://回复按钮--->回复该TopicReply
                showPopWindow(v,null);
                break;
            case R.id.AnswerReplyActivity_BtnReturn://返回
                ReplyAnswerActivity.this.finish();
                break;
            default:
                break;
        }
    }//end onClick
    /**
     *
     * @param v 弹出的回复窗的视图
     * @param theReplyAnswer 1、如果是null 则说明是回复TopicReply 2、如果非null 则说明是回复别人的ReplyAnswer
     */
    public void showPopWindow(View v, final ReplyAnswer theReplyAnswer){
        //可以使用同一个Layout布局文件
        View view = LayoutInflater.from(ReplyAnswerActivity.this).inflate(R.layout.topic_add_reply,null);
        myAnswerViewLayout = (LinearLayout)view.findViewById(R.id.mReplyViewLayout);
        myAnswerViewLayout.setBackgroundColor(getResources().getColor(R.color.color_ff));
        Button btnCommit = (Button)view.findViewById(R.id.commitBtn);
        final EditText editText = (EditText)view.findViewById(R.id.review_comment_edit) ;
        if(theReplyAnswer!=null)
            editText.setHint("回复： "+theReplyAnswer.getUserName());
        else
            editText.setHint("请回复该回答");
        //提交按钮 点击事件
        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = editText.getText().toString();
                //输出内容不为空
                if(!TextUtils.isEmpty(s.trim())){
                    String ReplyAnswerID="",
                            curUserID= MyApplication.user.getUserID(),
                            curUserName =MyApplication.user.getUserName();
                    String fromReplyID = receivedTopicReply.getReplyID();
                    String answerContent;
                    if(theReplyAnswer!=null){
                        answerContent = "回复"+receivedTopicReply.getUserName()+": "+s.trim();
                    }
                    else answerContent = s.trim();
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String answerDate = sdf.format(date);
                    final ReplyAnswer newReplyAnswer = new ReplyAnswer(ReplyAnswerID,curUserID,curUserName,fromReplyID,answerContent,answerDate);

                    String url = "http://192.168.191.1/Reading/ReplyServlet?Action=up&userID="
                            +curUserID+"&replyFromUserName="+curUserName+"&replyFromAnswerID="+fromReplyID+
                            "&date="+answerDate+"&replyContent="+answerContent;
                    abHttpUtil.get(url, new AbStringHttpResponseListener() {
                        @Override
                        public void onSuccess(int i, String s) {
                            answerListAdapter.addAnswer(newReplyAnswer);
                        }
                        @Override
                        public void onStart() {

                        }
                        @Override
                        public void onFinish() {

                        }
                        @Override
                        public void onFailure(int i, String s, Throwable throwable) {
                            showToast(ReplyAnswerActivity.this,"回复失败");
                        }
                    });
                    editText.setText("");
                    myPopupWindow.dismiss();
                }//end if isEmpty
                else
                    Toast.makeText(ReplyAnswerActivity.this,"输入内容不能为空",Toast.LENGTH_SHORT);
            }
        });

        //获取放PopWindow的位置
        //获取屏幕分辨率
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenWidth = metrics.widthPixels;
        myPopupWindow = new PopupWindow(view,mScreenWidth,200);
        myPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_OUTSIDE){
                    myPopupWindow.dismiss();
                }
                return false;
            }
        });
        myPopupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        myPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        myPopupWindow.setTouchable(true);
        myPopupWindow.setFocusable(true);
        myPopupWindow.setOutsideTouchable(true);
        myPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        myPopupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        myPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //从底部出现
        myPopupWindow.setAnimationStyle(R.style.GrowFromBottom);
        myPopupWindow.showAtLocation(findViewById(R.id.layout_all_of_answer), Gravity.BOTTOM |Gravity.CENTER_VERTICAL,0,0);
        //获取焦点
        editText.requestFocus();
    }//end showPopWindow method
}//end class
